package org.hepeng.workx.spring.cloud.netflix.ribbon.loadbalancer;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;
import org.apache.commons.lang3.StringUtils;
import org.hepeng.workx.spring.cloud.netflix.ribbon.RibbonRequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;


/**
 * @author he peng
 */
public class ServiceInstanceIdRule extends AbstractThreadIsolationRule {

    private static final Logger LOG = LoggerFactory.getLogger(ServiceInstanceIdRule.class);

    public ServiceInstanceIdRule() {}

    public ServiceInstanceIdRule(String instanceIdParamName) {
        super(instanceIdParamName);
    }

    public ServiceInstanceIdRule(String paramName, IRule rule) {
        super(paramName, rule);
    }

    @Override
    public List<Server> getParticipateLoadBalancingServers(Object key, RibbonRequestContext ribbonContext, List<Server> originalAllServers) {
        LOG.info("{} rules works" , ServiceInstanceIdRule.class.getName());

        List<Server> loadBalancingServers = new ArrayList<>();
        String paramInstanceId = getDecideLoadBalanceParam(ribbonContext);
        LOG.info("The specified routing instance id is {} " , paramInstanceId);

        for (Server server : originalAllServers) {
            String instanceId = server.getMetaInfo().getInstanceId();
            if (StringUtils.equals(paramInstanceId , instanceId)) {
                LOG.info("Matched server {} " , server);
                loadBalancingServers.add(server);
            }
        }
        return loadBalancingServers;
    }
}
